package servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.friend.dao.UserDAO;
import com.example.friend.pojo.User;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		// 设定编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String gender = req.getParameter("gender");
		
		String ageStr = req.getParameter("age");
		int age = Integer.parseInt(ageStr);
		
		String[] like = req.getParameterValues("like");
		
		PrintWriter pw = resp.getWriter();
		pw.println(username+"<br />");
		pw.println(password+"<br />");
		pw.println(gender+"<br />");
		pw.println(Arrays.toString(like)+"<br />");
		
		// 把用户信息放入一个User对象中
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		u.setAge(age);
		// 打球,下棋,打游戏
		String likeStr = "";
		for(int i=0;i<like.length;i++)
		{
			likeStr += like[i]+",";
		}
		u.setLike(likeStr);
		
		// 调用 DAO 实现注册
		UserDAO dao = new UserDAO();
		int result = 0;
		try {
			 result = dao.insert(u);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 根据注册结果显示
		if(result==1)
		{
			pw.print("<h1>注册成功</h1>");
		}
		else
		{
			pw.print("<h1>注册失败</h1>");
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doGet(req,resp);
	}
}
